package com.googlecode.spruce.plugins.core.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.io.IOUtils;

import com.googlecode.spruce.core.DefaultPluginResult;
import com.googlecode.spruce.core.ServiceCheckPlugin;
import com.googlecode.spruce.core.ServiceCheckPluginResult;

public class TcpServiceCheck implements ServiceCheckPlugin
{

    private String host;

    private int port;

    public ServiceCheckPluginResult execute()
    {
        final InetAddress ipAddress;
        Socket socket = null;

        try
        {
            ipAddress = InetAddress.getByName(this.host);
            socket = new Socket(ipAddress, this.port);
        }
        catch (final UnknownHostException e)
        {
            return new DefaultPluginResult(e);
        }
        catch (final IOException ioe)
        {
            return new DefaultPluginResult(ioe);
        }
        finally
        {
            IOUtils.closeQuietly(socket);
        }

        return new DefaultPluginResult(100);
    }

    /**
     * @return the host
     */
    public String getHost()
    {
        return host;
    }

    /**
     * @param host
     *            the host to set
     */
    public void setHost(final String host)
    {
        this.host = host;
    }

    /**
     * @return the port
     */
    public int getPort()
    {
        return port;
    }

    /**
     * @param port
     *            the port to set
     */
    public void setPort(final int port)
    {
        this.port = port;
    }

}
